package com.xxll.lockscreen;

import android.app.Activity;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity {

    public static final int RESULT_ENABLE = 1;
    ComponentName mDeviceComponentName /*= new ComponentName(getApplication(), DeviceAdminReceiver.class)*/;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

         mDeviceComponentName = new ComponentName(this, AdminChangeReceiver.class);
        if (!devicePolicyManager.isAdminActive(mDeviceComponentName)) {
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceComponentName);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "一键锁屏，需要您授予本APP管理设备(只是锁屏，没有其他多余操作)");
            startActivityForResult(intent, RESULT_ENABLE);
        } else {
            devicePolicyManager.lockNow();
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_ENABLE && resultCode == RESULT_OK) {
            finish();
        }
    }
}